import React, { useState, useEffect, useRef } from 'react'
import {
    Button,
    Modal,
    message,
    Tag,
    Space,
    Input,
    Select,
    Tooltip
} from 'antd'
import {
    DeleteOutlined,
    EditOutlined,
    RollbackOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons'
import './index.css'
import { getServiceListInformation } from '../../../utils/request/get.js'
import { deleteRecordById } from '../../../utils/request/delete.js'
import { useSelector } from 'react-redux'
import { formatTime, formatTimeLimit, getTime } from '../../../utils/time.js'
import NewService from './NewService'
import moment from 'moment'
import { findIdByName } from '../../../utils/array'
import { updateBankById, updateCustomerById, updateRecordById } from '../../../utils/request/put'
import { assignUndefinedValue, copy } from '../../../utils/common'
import ExportCSV from '../../../components/newsSandBox/ExportButton.js'
import MyTable from '../../../components/newsSandBox/MyTable.js'
import SearchItem from '../../../components/newsSandBox/SearchItem.js'

const { confirm } = Modal
const { Search } = Input

export default function UserList() {
    const [Records, setUserRecords] = useState([])
    const [dataSource, setDataSource] = useState([])
    const [showData, setShowData] = useState([])
    const [categories, setCategories] = useState([])
    const [services, setServices] = useState([])
    const [risks, setRisks] = useState([])
    const [header, setHeader] = useState({})
    const [headerNames, setHeaderNames] = useState([])
    const [loading, setLoading] = useState(true)
    const [isUpdateVisible, setIsUpdateVisible] = useState(false)
    const [isUpdateDisable, setIsUpdateDisable] = useState(false)
    const [selectChanged, setSelectChanged] = useState(false)
    const [currentRecord, serCurrentRecord] = useState(null)
    const [total, setTotal] = useState(0)
    const [selectedValue, setSelectedValue] = useState(null)
    const [searchValue, setSearchValue] = useState(null)

    const token = useSelector(state => state.TokenReducer.token)
    const { userId } = token
    const updateForm = useRef(null)
    const defaultTitle = "查询失败"

    useEffect(() => {
        async function fetchData() {
            if (token) {
                const res = await getServiceListInformation(token)
                if (res) {
                    const { list, Records } = res
                    if (Records) {
                        setCategories(Records.categories)
                        setServices(Records.services)
                        setRisks(Records.risks)
                        setUserRecords(Records)
                        setHeader(Records.headers[0])
                        setHeaderNames(checkName(Records.headers[0]))
                    }
                    if (list) {
                        setTotal(list.length)
                        setDataSource(list)
                        setShowData(list)
                    }
                }
                setLoading(false)
            }
        }
        fetchData()
    }, [token])

    /**
     * 
     * @param {标题对象} header 
     * @returns 筛选出不用展示部分
     */
    const checkName = (header) => {
        let names = []
        let count = 1
        Object.keys(header).forEach(item => {
            if (item !== 'id' && item !== 'createdAt' && item !== 'updatedAt') {
                names.push({ id: count, key: item, title: header[item] })
                count++
            }
        })
        return names
    }

    const deleteData = async (item) => {
        setTotal(t => t - 1)
        setShowData(showData.filter(data => data.id !== item.id))
        setDataSource(dataSource.filter(data => data.id !== item.id))
        const res = await deleteRecordById(item.id)
        if (res) {
            message.success(res.data.msg)
        } else {
            message.error(res.data.msg)
        }
    }

    const showError = (err) => {
        const errors = err.errorFields
        if (errors.length > 0) {
            message.warning(errors[0].errors[0])
        }
    }

    const updateRecord = async (value) => {
        const {
            categoryName, serviceName, channel, location, eLocation, notes, auditState,
            customerName, code, unitName, identityId, phoneNumber,
            bankName, owner, number
        } = value
        const { categories, services, customers, banks, auditStates, channels, locations } = Records
        const categoryId = findIdByName(categories, categoryName)
        const serviceId = findIdByName(services, serviceName)
        const customerId = findIdByName(customers, identityId)
        const bankId = findIdByName(banks, bankName)
        const auditId = findIdByName(auditStates, auditState)
        const channelId = findIdByName(channels, channel)
        const locationId = findIdByName(locations, location)
        const auditUserId = token.userId

        const acceptedTime = getTime(value.acceptedTime)
        const endTime = getTime(value.endTime)
        // 处理客户
        let customer = {
            name: customerName,
            identityId,
            code: assignUndefinedValue(code),
            unitName: assignUndefinedValue(unitName),
            phoneNumber: assignUndefinedValue(phoneNumber)
        }
        if (customerId) {
            const customerRes = await updateCustomerById(customerId, customer)
            if (customerRes.status !== 200) {
                message.error(customerRes.data.msg)
                return
            }
        }
        const bankRecord = {
            name: bankName,
            owner: assignUndefinedValue(owner),
            number: assignUndefinedValue(number),
        }
        if (bankId) {
            const bankRes = await updateBankById(bankId, bankRecord)
            if (bankRes.status !== 200) {
                message.error(bankRes.data.msg)
                return
            }
        }

        if (categoryId && serviceId && customerId && channelId && locationId) {
            // 处理业务记录
            let obj = {
                categoryId, serviceId, customerId, channelId, locationId, eLocation, userId, bankId,
                acceptedTime, endTime, auditUserId,
                notes: assignUndefinedValue(notes),
                auditId
            }
            // console.log(obj);
            if (checkObjectIsNull(obj)) {
                message.error("请检查信息完整")
            } else {
                const recordRes = await updateRecordById(currentRecord.id, obj)
                if (recordRes.status === 200) {
                    message.success("更新成功")
                    return true
                } else {
                    message.info(recordRes.msg)
                    return false
                }
            }
        }
    }

    const checkObjectIsNull = (obj) => {
        for (const key in obj) {
            if (Object.hasOwnProperty.call(obj, key)) {
                const element = obj[key];
                if (key !== 'notes' && !element) return true
            }
        }
        return false
    }

    const updateFormMethod = () => {
        updateForm.current.validateFields().then(value => {
            setIsUpdateVisible(false)
            setIsUpdateDisable(!isUpdateDisable)
            if (updateRecord(value)) {
                setShowData(showData.map(item => {
                    if (item.id === currentRecord.id) {
                        return {
                            ...item,
                            ...value,
                            acceptedTime: getTime(value.acceptedTime),
                            endTime: getTime(value.endTime)
                        }
                    }
                    return item
                }))
            }
        }).catch(err => { showError(err) })
    }

    const showUpdateForm = (item) => {
        // console.log(item);
        const obj = {
            ...item,
            acceptedTime: moment(item.acceptedTime),
            endTime: moment(item.endTime)
        }
        // react中状态更新不一定是同步的，导致表单还没挂载就调用了setFieldsValue，所以报错
        setIsUpdateVisible(true)
        // 解决办法： 等待表单显示（即挂载完成）再向下执行
        setTimeout(() => { // 将 表单挂载 和 设置表单的值 这两步操作变成同步执行（即一步步执行）
            updateForm.current?.setFieldsValue(obj)
        }, 0)
        serCurrentRecord(obj)
    }

    const showConfirm = (type, item) => {
        let obj = {
            icon: <ExclamationCircleOutlined />,
        }
        switch (type) {
            case 'CANCEL':
                obj.title = '您确定要取消吗?'
                obj.onOk = function () { }
                obj.onCancel = function () { console.log('Cancel'); }
                break
            case 'DELETE':
                obj.title = '您确定要删除吗?'
                obj.cancelText = '取消'
                obj.okText = '确定'
                obj.onOk = function () { deleteData(item); }
                obj.onCancel = function () { console.log('Cancel'); }
                break
            default: break
        }
        confirm(obj)
    };

    const columns = [
        {
            title: header['categoryName'],
            dataIndex: 'categoryName',
            width: 90,
            fixed: 'left',
            // defaultSortOrder: 'descend',
            onCell: record => ({
                onClick: () => {
                    copy(record.categoryName)
                }
            }),
            sorter: (a, b) => {
                // 按 id 升序排列
                return a.Category.id - b.Category.id
            },
            filters: [...categories.map(item => ({
                text: item.title, value: item.title,
            }))],
            onFilter: (value, record) => {
                // value 是要筛选的内容 record 是所有内容
                // console.log(value, record);
                // console.log(record);
                // 只展示true的部分
                return record.categoryName.indexOf(value) === 0
            },
            render: (title) => {
                return <b>{title === "" ? defaultTitle : title}</b>
            }
        },
        {
            title: header['serviceName'],
            dataIndex: 'serviceName',
            width: 105,
            fixed: 'left',
            onCell: record => ({
                onClick: () => {
                    copy(record.serviceName)
                }
            }),
            filters: [...services.map(item => ({
                text: item.title, value: item.title,
            }))],
            onFilter: (value, record) => record.serviceName.indexOf(value) === 0,
        },
        {
            title: header['circulation'],
            dataIndex: 'circulation',
            width: 70
        },
        {
            title: header['type'],
            dataIndex: 'type',
            width: 70,
        },
        {
            title: header['risk'],
            dataIndex: 'risk',
            width: 70,
            filters: [...risks.map(item => ({
                text: item.title, value: item.title,
            }))],
            onFilter: (value, record) => record.risk.indexOf(value) === 0,
            render: (level) => {
                switch (level) {
                    case "暂无":
                        return <Tag color='green'>{level}</Tag>
                    case "低等":
                        return <Tag color='orange'>{level}</Tag>
                    case "中等":
                        return <Tag color='purple'>{level}</Tag>
                    case "高等":
                        return <Tag color='red'>{level}</Tag>
                    default:
                        return <Tag color='error'>{level}</Tag>
                }
            }
        },
        {
            title: header['timeLimit'],
            dataIndex: 'timeLimit',
            width: 70,
            sorter: (a, b) => {
                return a.timeLimit - b.timeLimit
            },
            render: (value) => {
                return formatTimeLimit(value)
            }
        },
        {
            title: header['unitName'],
            dataIndex: 'unitName',
            width: 70,
            onCell: record => ({
                onClick: () => {
                    copy(record.unitName)
                }
            }),
        },
        {
            title: header['code'],
            dataIndex: 'code',
            width: 70,
            onCell: record => ({
                onClick: () => {
                    copy(record.code)
                }
            }),
        },
        {
            title: header['customerName'],
            dataIndex: 'customerName',
            width: 60,
            onCell: record => ({
                onClick: () => {
                    copy(record.customerName)
                }
            }),
        },
        {
            title: header['identityId'],
            dataIndex: 'identityId',
            width: 70,
            onCell: record => ({
                onClick: () => {
                    copy(record.identityId)
                }
            }),
        },
        {
            title: header['channel'],
            dataIndex: 'channel',
            width: 60,
        },
        {
            title: header['location'],
            dataIndex: 'location',
            width: 70
        },
        {
            title: header['eLocation'],
            dataIndex: 'eLocation',
            width: 70,
            onCell: record => ({
                onClick: () => {
                    copy(record.eLocation)
                }
            }),
        },
        {
            title: header['username'],
            dataIndex: 'username',
            width: 50
        },
        {
            title: header['acceptedTime'],
            dataIndex: 'acceptedTime',
            width: 70,
            onCell: record => ({
                onClick: () => {
                    copy(record.acceptedTime)
                }
            }),
            sorter: (a, b) => {
                return new Date(a.acceptedTime) - new Date(b.acceptedTime)
            },
            render: (time) => {
                return formatTime(time)
            }
        },
        {
            title: header['endTime'],
            dataIndex: 'endTime',
            width: 100,
            onCell: record => ({
                onClick: () => {
                    copy(record.endTime)
                }
            }),
            sorter: (a, b) => {
                return new Date(a.endTime) - new Date(b.endTime)
            },
            render: (time) => {
                return formatTime(time)
            }
        },
        {
            title: header['phoneNumber'],
            dataIndex: 'phoneNumber',
            width: 70,
            onCell: record => ({
                onClick: () => {
                    copy(record.phoneNumber)
                }
            }),

        },
        {
            title: header['bankName'],
            dataIndex: 'bankName',
            width: 90
        },
        {
            title: header['owner'],
            dataIndex: 'owner',
            width: 100
        },
        {
            title: header['number'],
            dataIndex: 'number',
            width: 100
        },
        {
            title: header['notes'],
            dataIndex: 'notes',
            width: 70
        },
        {
            title: header['auditState'],
            dataIndex: 'auditState',
            width: 70,
            render: (auditState) => {
                switch (auditState) {
                    case "未审核":
                        return <Tag color='blue'>{auditState}</Tag>
                    case "审核中":
                        return <Tag color='yellow'>{auditState}</Tag>
                    case "已通过":
                        return <Tag color='green'>{auditState}</Tag>
                    case "未通过":
                        return <Tag color='red'>{auditState}</Tag>
                    default:
                        return <Tag color='error'>{"暂无数据"}</Tag>
                }
            }
        },
        {
            title: header['auditSuggest'],
            dataIndex: 'auditSuggest',
            width: 70,
            render: (auditSuggest) => {
                return auditSuggest
            }
        },
        {
            title: '操作',
            fixed: 'right',
            width: 70,
            render: (record) => {
                return (
                    <div>
                        <Button
                            disabled={record.default}
                            danger onClick={() => showConfirm("DELETE", record)}
                            shape="circle" icon={<DeleteOutlined />}>
                        </Button>&nbsp;&nbsp;
                        <Button
                            disabled={record.default}
                            shape="circle"
                            icon={<EditOutlined />}
                            type="primary"
                            onClick={() => { showUpdateForm(record) }}></Button>
                    </div>
                )
            }
        }
    ]

    const handleTableChange = (pagination, filters, sorter, extra) => {
        let showDatas = dataSource;

        // 遍历 filters 对象中的所有属性
        Object.keys(filters).forEach(filterKey => {
            const filterValues = filters[filterKey];

            if (filterValues && filterValues.length > 0) {
                showDatas = showDatas.filter(item => {
                    // 使用 indexOf 判断是否包含筛选条件
                    return filterValues.some(value => item[filterKey].indexOf(value) === 0);
                });
            }
        });

        // 更新显示数据和总数
        setShowData(showDatas);
        setTotal(showDatas.length);
    }

    const formatExportData = (data) => {
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            item["acceptedTime"] = formatTime(item["acceptedTime"])
            item["endTime"] = formatTime(item["endTime"])
        }
        return data
    }

    const handleSelect = (value, option) => {
        setSelectedValue(option)
    }

    const onSearch = (searchValue) => {
        setSearchValue(searchValue)
        if (!selectedValue) {
            message.error('搜索项不可为空')
            return
        }
        if (!searchValue) {
            message.error('搜索内容不可为空')
            return
        }
        const { value } = selectedValue
        const filteredData = searchWithType(value, searchValue)
        setShowData(filteredData)
        setTotal(filteredData.length)
    }

    // 处理点击返回按钮的函数
    const handleReturnButtonClick = () => {
        // 恢复原始表格状态
        setSelectedValue(null)
        setSearchValue('')
        setShowData(dataSource);
        setTotal(dataSource.length);
        setSelectChanged(false); // 确保监测表格变化的状态正常
    };

    /**
     * 
     * @param {搜索的类型} type 
     * @param {搜索的值} value 
     * @returns 同一类型下与搜索值相等的结果
     */
    const searchWithType = (type, value) => {
        setSelectChanged(true)
        const result = dataSource.filter(element => {
            const elementValue = element[type]
            if (typeof elementValue === 'number') {
                return element[type].toString().includes(value)
            }
            return elementValue.includes(value)
        });
        return result
    }

    const handleSearchFinish = (value, name) => {
        // console.log(name);
        const filteredData = searchWithType(name, value)
        setShowData(filteredData)
        setTotal(filteredData.length)
    }

    return (
        <>
            {dataSource.length !== 0 &&
                <ExportCSV data={formatExportData(showData)} header={header} fileName={"业务列表"} />}
            <div className='search-area'>
                <Space size="small" wrap={true}>
                    {/* 返回按钮 */}
                    <Tooltip placement="top" title={'点击清空'} >
                        <Button icon={<RollbackOutlined />} onClick={handleReturnButtonClick} />
                    </Tooltip>
                    <Select
                        value={selectedValue}
                        placeholder="搜索项"
                        style={{ width: 120 }}
                        onChange={handleSelect}>
                        {
                            headerNames && headerNames.map(item => {
                                return <Select.Option key={item.id} value={item.key}>{item.title}</Select.Option>
                            })
                        }
                    </Select>
                    <Search
                        value={searchValue}
                        allowClear
                        placeholder="请输入搜索内容"
                        onChange={(e) => setSearchValue(e.target.value)}
                        onSearch={onSearch}
                        style={{
                            width: 180,
                        }}
                    />
                    <SearchItem title='身份证号' name="identityId" onFinish={handleSearchFinish} />
                    <SearchItem title='手机号' name="phoneNumber" onFinish={handleSearchFinish} />
                    <SearchItem title='单位名称' name="unitName" onFinish={handleSearchFinish} />
                    <SearchItem title='姓名（医保负责人）' name="customerName" onFinish={handleSearchFinish} />
                </Space>
            </div>
            <MyTable
                pageSize={5}
                total={total}
                dataSource={showData}
                columns={columns}
                onChange={selectChanged ? null : handleTableChange}
                loading={loading}
                params={{
                    size: 'middle',
                    bordered: true,
                    rowClassName: { textAlign: 'center' },
                    scroll: {
                        x: 3000,
                        y: 400,
                    }
                }}
            />
            <Modal
                className='recordModal'
                open={isUpdateVisible}
                title="更新记录"
                okText="更新"
                cancelText="取消"
                onCancel={() => {
                    setIsUpdateVisible(false)
                    setIsUpdateDisable(!isUpdateDisable)
                }
                }
                onOk={() => updateFormMethod()}
            >
                <NewService ref={updateForm} isUpdate={true} data={currentRecord}></NewService>
            </Modal>
        </>
    )
}